// Game constants
const TILE_SIZE = 32;
const SPRITE_SIZE = 32;
const PLAYER_SPEED = 3;

// Directions
const DIRECTIONS = {
    DOWN: 0,
    LEFT: 1,
    RIGHT: 2,
    UP: 3
};

// Map manager instance
let mapManager = null;

// Enhanced map system
class GameMap {
    constructor(mapData) {
        this.mapData = mapData;
        this.width = mapData.size.width;
        this.height = mapData.size.height;
        this.tiles = [];
        this.spawnPoints = [];
        this.portals = mapData.portals || [];
        this.tileTypes = mapData.tileTypes;
    }

    generate() {
        // Initialize tiles array
        this.tiles = [];
        
        // Generate base map based on tile types
        for (let y = 0; y < this.height; y++) {
            this.tiles[y] = [];
            for (let x = 0; x < this.width; x++) {
                this.tiles[y][x] = 'grass'; // Default tile
            }
        }

        // Add random obstacles based on map type
        this.addRandomObstacles();
        
        // Add spawn points
        this.generateSpawnPoints();
        
        console.log(`地图生成完成: ${this.mapData.name} (${this.width}x${this.height}), 生成点: ${this.spawnPoints.length}`);
    }

    addRandomObstacles() {
        const obstacleCount = Math.floor(this.width * this.height * 0.1); // 10% obstacles
        
        for (let i = 0; i < obstacleCount; i++) {
            const x = Math.floor(Math.random() * this.width);
            const y = Math.floor(Math.random() * this.height);
            
            if (this.tiles[y] && this.tiles[y][x] !== undefined) {
                // Choose obstacle type based on map
                const obstacleTypes = Object.keys(this.tileTypes).filter(key => 
                    key !== 'grass' && !this.tileTypes[key].walkable
                );
                
                if (obstacleTypes.length > 0) {
                    const obstacleType = obstacleTypes[Math.floor(Math.random() * obstacleTypes.length)];
                    this.tiles[y][x] = obstacleType;
                }
            }
        }
    }

    generateSpawnPoints() {
        this.spawnPoints = [];
        const spawnCount = this.mapData.monsterCount || 10;
        
        for (let i = 0; i < spawnCount; i++) {
            let attempts = 0;
            while (attempts < 50) {
            const x = Math.floor(Math.random() * this.width);
            const y = Math.floor(Math.random() * this.height);
                
                if (this.isWalkable(x, y)) {
                this.spawnPoints.push({ x, y });
                    break;
                }
                attempts++;
            }
        }
    }

    getSpawnPoint() {
        if (this.spawnPoints.length === 0) return null;
        const index = Math.floor(Math.random() * this.spawnPoints.length);
        return this.spawnPoints[index];
    }

    isWalkable(x, y) {
        // Ensure coordinates are integers and within bounds
        const tileX = Math.floor(x);
        const tileY = Math.floor(y);
        
        if (tileX < 0 || tileX >= this.width || tileY < 0 || tileY >= this.height) {
            return false;
        }
        
        // Check if the tile exists and is walkable
        if (this.tiles[tileY] && this.tiles[tileY][tileX] !== undefined) {
            const tileType = this.tiles[tileY][tileX];
            return this.tileTypes[tileType] ? this.tileTypes[tileType].walkable : false;
        }
        
        return false; // Default to not walkable if tile doesn't exist
    }

    draw(ctx, camera) {
        const tileSize = TILE_SIZE;
        const startX = Math.floor(camera.x / tileSize);
        const startY = Math.floor(camera.y / tileSize);
        const endX = startX + Math.ceil(ctx.canvas.width / tileSize) + 1;
        const endY = startY + Math.ceil(ctx.canvas.height / tileSize) + 1;

        // Draw background
        ctx.fillStyle = this.mapData.background;
        ctx.fillRect(-camera.x, -camera.y, ctx.canvas.width, ctx.canvas.height);

        for (let y = startY; y < endY; y++) {
            for (let x = startX; x < endX; x++) {
                if (x >= 0 && x < this.width && y >= 0 && y < this.height) {
                    // Check if the tile exists before accessing it
                    if (this.tiles[y] && this.tiles[y][x] !== undefined) {
                        const tileType = this.tiles[y][x];
                        const screenX = x * tileSize - camera.x;
                        const screenY = y * tileSize - camera.y;

                        if (this.tileTypes[tileType]) {
                            ctx.fillStyle = this.tileTypes[tileType].color;
                            ctx.fillRect(screenX, screenY, tileSize, tileSize);
                        }
                    }
                }
            }
        }

        // Draw portals
        this.drawPortals(ctx, camera);
    }

    drawPortals(ctx, camera) {
        if (!this.portals) return;

        this.portals.forEach(portal => {
            const screenX = portal.x * TILE_SIZE - camera.x;
            const screenY = portal.y * TILE_SIZE - camera.y;
            
            // Draw portal as a glowing circle
            ctx.save();
            ctx.globalAlpha = 0.8;
            ctx.fillStyle = '#9C27B0';
            ctx.beginPath();
            ctx.arc(screenX + TILE_SIZE/2, screenY + TILE_SIZE/2, TILE_SIZE/2, 0, Math.PI * 2);
            ctx.fill();
            
            // Draw portal border
            ctx.strokeStyle = '#E91E63';
            ctx.lineWidth = 3;
            ctx.stroke();
            ctx.restore();
        });
    }

    // Check if player is near a portal
    checkPortal(playerX, playerY) {
        if (!this.portals) return null;

        for (const portal of this.portals) {
            const distance = Math.sqrt(
                Math.pow(playerX / 32 - portal.x, 2) + 
                Math.pow(playerY / 32 - portal.y, 2)
            );
            
            if (distance < 2) { // 2格范围内触发传送门
                return portal;
            }
        }
        return null;
    }
}

// Monster types (will be extended by map manager)
const MONSTER_TYPES = {
    SLIME: {
        name: '史莱姆',
        health: 50,
        damage: 5,
        exp: 20,
        color: '#4CAF50',
        dropRate: 0.8,
        level: 1
    },
    SKELETON: {
        name: '骷髅战士',
        health: 80,
        damage: 8,
        exp: 35,
        color: '#9E9E9E',
        dropRate: 0.85,
        level: 2
    },
    ORC: {
        name: '兽人战士',
        health: 120,
        damage: 12,
        exp: 50,
        color: '#795548',
        dropRate: 0.9,
        level: 3
    },
    DRAGON: {
        name: '幼龙',
        health: 200,
        damage: 25,
        exp: 100,
        color: '#FF5722',
        dropRate: 0.95,
        level: 5
    },
    PHOENIX: {
        name: '火凤凰',
        health: 300,
        damage: 35,
        exp: 150,
        color: '#FF9800',
        dropRate: 1.0,
        level: 7
    }
};

// Simple item types
const ITEM_TYPES = [
    // Weapons
    { name: '木剑', type: 'weapon', damage: 5, color: '#8B4513' },
    { name: '铁剑', type: 'weapon', damage: 15, color: '#FFD700' },
    { name: '精钢剑', type: 'weapon', damage: 25, color: '#C0C0C0' },
    { name: '魔法剑', type: 'weapon', damage: 35, color: '#9370DB' },
    
    // Armor
    { name: '皮甲', type: 'armor', defense: 5, color: '#8B4513' },
    { name: '铁甲', type: 'armor', defense: 15, color: '#C0C0C0' },
    { name: '精钢甲', type: 'armor', defense: 25, color: '#4682B4' },
    { name: '魔法甲', type: 'armor', defense: 35, color: '#9370DB' },
    
    // Accessories
    { name: '力量戒指', type: 'accessory', damage: 10, color: '#FFD700' },
    { name: '守护项链', type: 'accessory', defense: 10, color: '#00CED1' },
    { name: '生命戒指', type: 'accessory', health: 50, color: '#FF69B4' },
    
    // Consumables
    { name: '生命药水', type: 'potion', healing: 50, color: '#FF0000' },
    { name: '大生命药水', type: 'potion', healing: 100, color: '#DC143C' }
];

// Game state
let gameState = {
    player: {
        x: 100,
        y: 100,
        level: 1,
        exp: 0,
        maxExp: 100,
        health: 100,
        maxHealth: 100,
        mana: 100,
        maxMana: 100,
        damage: 10,
        defense: 5,
        speed: 3,
        inventory: [],
        equipment: {
            weapon: null,
            chest: null,
            rings: []
        },
        direction: DIRECTIONS.DOWN,
        moving: false,
        inCombat: false,
        skills: {
            heal: { name: '治疗术', damage: 0, healing: 30, mana: 15, maxCooldown: 120, cooldown: 0 },
            fireball: { name: '火球术', damage: 25, healing: 0, mana: 20, maxCooldown: 60, cooldown: 0 },
            lightning: { name: '闪电术', damage: 35, healing: 0, mana: 25, maxCooldown: 90, cooldown: 0 }
        }
    },
    monsters: [],
    items: [],
    currentMap: null,
    camera: {
        x: 0,
        y: 0
    },
    settings: {
        autoPotion: true,
        autoPotionThreshold: 0.3,
        autoEquip: true
    }
};

// Canvas setup
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// Set canvas size
function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    console.log('Canvas resized to:', canvas.width, 'x', canvas.height);
}

window.addEventListener('resize', resizeCanvas);
resizeCanvas();

// Global key state
const keys = {};

// Initialize player equipment
function initPlayerEquipment() {
    if (!gameState.player.equipment) {
        gameState.player.equipment = {
            weapon: null,
            chest: null,
            rings: []
        };
    }
    
    console.log('玩家装备系统初始化完成');
}

// Spawn monsters function
function spawnMonsters() {
    if (!mapManager || !gameState.currentMap) return;
    
    const currentMapData = mapManager.getCurrentMap();
    const maxMonsters = currentMapData.monsterCount || 10;
    
    if (gameState.monsters.length < maxMonsters) {
        // Get available monster types for current map
        const availableMonsterTypes = currentMapData.monsterTypes.map(type => MONSTER_TYPES[type]);
        const monsterType = availableMonsterTypes[Math.floor(Math.random() * availableMonsterTypes.length)];
        
        const spawnPoint = gameState.currentMap.getSpawnPoint();
        if (spawnPoint) {
            // Generate monster level based on map level range
            const levelRange = currentMapData.monsterLevelRange;
            const monsterLevel = Math.floor(Math.random() * (levelRange[1] - levelRange[0] + 1)) + levelRange[0];
            
            // Scale monster stats based on level
            const levelMultiplier = 1 + (monsterLevel - 1) * 0.3;
            const scaledHealth = Math.floor(monsterType.health * levelMultiplier);
            const scaledDamage = Math.floor(monsterType.damage * levelMultiplier);
            const scaledExp = Math.floor(monsterType.exp * levelMultiplier);
            
            const monster = {
                ...monsterType,
                x: spawnPoint.x * TILE_SIZE + Math.random() * TILE_SIZE,
                y: spawnPoint.y * TILE_SIZE + Math.random() * TILE_SIZE,
                health: scaledHealth,
                maxHealth: scaledHealth,
                damage: scaledDamage,
                exp: scaledExp,
                level: monsterLevel
            };
            gameState.monsters.push(monster);
            
            console.log(`生成怪物: ${monster.name} Lv.${monster.level} (${monster.health}HP, ${monster.damage}ATK)`);
        }
    }
}

// Draw player function
function drawPlayer(ctx) {
    ctx.fillStyle = '#2196F3';
    ctx.fillRect(
        gameState.player.x - TILE_SIZE/2,
        gameState.player.y - TILE_SIZE/2,
        TILE_SIZE,
        TILE_SIZE
    );

    // Draw player direction indicator
    ctx.fillStyle = '#ffffff';
    ctx.beginPath();
    if (gameState.player.direction === DIRECTIONS.UP) {
        ctx.arc(gameState.player.x, gameState.player.y - TILE_SIZE/4, 3, 0, Math.PI * 2);
    } else if (gameState.player.direction === DIRECTIONS.DOWN) {
        ctx.arc(gameState.player.x, gameState.player.y + TILE_SIZE/4, 3, 0, Math.PI * 2);
    } else if (gameState.player.direction === DIRECTIONS.LEFT) {
        ctx.arc(gameState.player.x - TILE_SIZE/4, gameState.player.y, 3, 0, Math.PI * 2);
    } else if (gameState.player.direction === DIRECTIONS.RIGHT) {
        ctx.arc(gameState.player.x + TILE_SIZE/4, gameState.player.y, 3, 0, Math.PI * 2);
    }
    ctx.fill();
}

// Draw monsters function with enhanced UI
function drawMonsters(ctx) {
    gameState.monsters.forEach(monster => {
        // Draw monster body with shadow
        ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
        ctx.shadowBlur = 4;
        ctx.shadowOffsetX = 2;
        ctx.shadowOffsetY = 2;
        
        ctx.fillStyle = monster.color;
        ctx.fillRect(
            monster.x - TILE_SIZE/2,
            monster.y - TILE_SIZE/2,
            TILE_SIZE,
            TILE_SIZE
        );
        
        // Reset shadow
        ctx.shadowColor = 'transparent';
        ctx.shadowBlur = 0;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;

        // Draw monster name with enhanced styling
        ctx.fillStyle = '#ffffff';
        ctx.font = 'bold 14px Arial';
        ctx.textAlign = 'center';
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 3;
        ctx.strokeText(
            monster.name,
            monster.x,
            monster.y - TILE_SIZE/2 - 30
        );
        ctx.fillText(
            monster.name,
            monster.x,
            monster.y - TILE_SIZE/2 - 30
        );

        // Draw level with enhanced styling
        ctx.fillStyle = '#FFD700';
        ctx.font = 'bold 12px Arial';
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 2;
        ctx.strokeText(
            `Lv.${monster.level}`,
            monster.x,
            monster.y - TILE_SIZE/2 - 45
        );
        ctx.fillText(
            `Lv.${monster.level}`,
            monster.x,
            monster.y - TILE_SIZE/2 - 45
        );

        // Draw enhanced health bar
        const healthBarWidth = TILE_SIZE + 8;
        const healthBarHeight = 8;
        const healthBarX = monster.x - healthBarWidth/2;
        const healthBarY = monster.y - TILE_SIZE/2 - 20;

        // Health bar background with border
        ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        ctx.fillRect(healthBarX - 2, healthBarY - 2, healthBarWidth + 4, healthBarHeight + 4);
        
        // Health bar container
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight);

        // Health bar fill with dynamic color
        const healthPercent = monster.health / monster.maxHealth;
        if (healthPercent > 0.6) {
            ctx.fillStyle = '#00ff00';
        } else if (healthPercent > 0.3) {
            ctx.fillStyle = '#ffff00';
        } else {
            ctx.fillStyle = '#ff0000';
        }
        
        ctx.fillRect(healthBarX, healthBarY, healthBarWidth * healthPercent, healthBarHeight);

        // Health bar border
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 1;
        ctx.strokeRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight);

        // Health text with enhanced styling
        ctx.fillStyle = '#ffffff';
        ctx.font = 'bold 11px Arial';
        ctx.textAlign = 'center';
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 2;
        ctx.strokeText(
            `${monster.health}/${monster.maxHealth}`,
            monster.x,
            monster.y - TILE_SIZE/2 - 8
        );
        ctx.fillText(
            `${monster.health}/${monster.maxHealth}`,
            monster.x,
            monster.y - TILE_SIZE/2 - 8
        );
    });
}

// Draw items function
function drawItems(ctx) {
    gameState.items.forEach(item => {
        ctx.fillStyle = item.color;
        ctx.fillRect(
            item.x - TILE_SIZE/4,
            item.y - TILE_SIZE/4,
            TILE_SIZE/2,
            TILE_SIZE/2
        );
    });
}

// Create inventory slots
function createInventorySlots() {
    const inventorySlots = document.getElementById('inventory-slots');
    if (!inventorySlots) {
        console.error('找不到inventory-slots元素');
        return;
    }
    
    // Clear existing slots
    inventorySlots.innerHTML = '';
    
    // Create 20 inventory slots
    for (let i = 0; i < 20; i++) {
        const slot = document.createElement('div');
        slot.className = 'inventory-slot empty';
        slot.id = `slot-${i}`;
        slot.textContent = '-';
        
        // Add click event for item interaction
        slot.addEventListener('click', () => {
            if (gameState.player.inventory[i]) {
                const item = gameState.player.inventory[i];
                console.log(`点击物品: ${item.name}`);
                
                // Auto equip if it's equipment
                if (item.type === 'weapon' || item.type === 'armor' || item.type === 'accessory') {
                    if (autoEquipItem(item)) {
                        // Remove from inventory
                        gameState.player.inventory.splice(i, 1);
                        updateInventoryDisplay();
    updateUI();
                    }
                } else if (item.type === 'potion') {
                    // Use potion
                    if (item.healing) {
                        gameState.player.health = Math.min(gameState.player.maxHealth, gameState.player.health + item.healing);
                        gameState.player.inventory.splice(i, 1);
                        updateInventoryDisplay();
                        updateUI();
                        console.log(`使用药水，恢复${item.healing}点生命值`);
                    }
                }
            }
        });
        
        inventorySlots.appendChild(slot);
    }
    
    console.log('背包格子创建完成，共20个槽位');
}

// Update inventory display
function updateInventoryDisplay() {
    const inventorySlots = document.getElementById('inventory-slots');
    if (!inventorySlots) return;
    
    // Clear all slots
    for (let i = 0; i < 20; i++) {
        const slot = document.getElementById(`slot-${i}`);
        if (slot) {
            slot.className = 'inventory-slot empty';
            slot.textContent = '-';
        }
    }
    
    // Fill slots with items
    gameState.player.inventory.forEach((item, index) => {
        if (index < 20) {
            const slot = document.getElementById(`slot-${index}`);
            if (slot) {
                slot.className = 'inventory-slot';
                slot.textContent = item.name;
                slot.style.background = item.color;
                slot.title = `${item.name}\n类型: ${item.type}`;
            }
        }
    });
}

// Auto equip item
function autoEquipItem(item) {
    if (!gameState.player.equipment) {
        initPlayerEquipment();
    }
    
    let equipped = false;
    let oldItem = null;
    
    if (item.type === 'weapon') {
        if (!gameState.player.equipment.weapon || 
            item.damage > gameState.player.equipment.weapon.damage) {
            // Unequip old weapon
    if (gameState.player.equipment.weapon) {
                oldItem = gameState.player.equipment.weapon;
                gameState.player.damage -= gameState.player.equipment.weapon.damage;
                console.log(`卸下旧武器: ${oldItem.name}`);
            }
            // Equip new weapon
            gameState.player.equipment.weapon = item;
            gameState.player.damage += item.damage;
            equipped = true;
            console.log(`自动装备武器: ${item.name}，攻击力+${item.damage}`);
            
            // Add old weapon to inventory if exists
            if (oldItem) {
                addItemToInventory(oldItem);
            }
        } else {
            console.log(`当前武器更好，不替换: ${gameState.player.equipment.weapon.name}`);
        }
    } else if (item.type === 'armor') {
        if (!gameState.player.equipment.chest || 
            item.defense > gameState.player.equipment.chest.defense) {
            // Unequip old armor
            if (gameState.player.equipment.chest) {
                oldItem = gameState.player.equipment.chest;
                gameState.player.defense -= gameState.player.equipment.chest.defense;
                if (gameState.player.equipment.chest.health) {
                    gameState.player.maxHealth -= gameState.player.equipment.chest.health;
                    if (gameState.player.health > gameState.player.maxHealth) {
                        gameState.player.health = gameState.player.maxHealth;
                    }
                }
                console.log(`卸下旧护甲: ${oldItem.name}`);
            }
            // Equip new armor
            gameState.player.equipment.chest = item;
            gameState.player.defense += item.defense;
            if (item.health) {
                gameState.player.maxHealth += item.health;
                gameState.player.health += item.health;
            }
            equipped = true;
            console.log(`自动装备护甲: ${item.name}，防御力+${item.defense}${item.health ? `，生命值+${item.health}` : ''}`);
            
            // Add old armor to inventory if exists
            if (oldItem) {
                addItemToInventory(oldItem);
        }
    } else {
            console.log(`当前护甲更好，不替换: ${gameState.player.equipment.chest.name}`);
        }
    } else if (item.type === 'accessory') {
        // Check if we have space for rings
        if (gameState.player.equipment.rings.length < 2) {
            gameState.player.equipment.rings.push(item);
            // Apply ring effects
            if (item.damage) gameState.player.damage += item.damage;
            if (item.defense) gameState.player.defense += item.defense;
            if (item.health) {
                gameState.player.maxHealth += item.health;
                gameState.player.health += item.health;
            }
            if (item.speed) gameState.player.speed += item.speed;
            equipped = true;
            console.log(`自动装备饰品: ${item.name}${item.damage ? `，攻击力+${item.damage}` : ''}${item.defense ? `，防御力+${item.defense}` : ''}${item.health ? `，生命值+${item.health}` : ''}${item.speed ? `，速度+${item.speed}` : ''}`);
        } else {
            console.log('饰品槽位已满，无法装备更多饰品');
        }
    }
    
    if (equipped) {
        updateUI();
        // Show equipment notification
        showEquipmentNotification(item.name, '装备');
    }
    
    return equipped;
}

// Add item to inventory
function addItemToInventory(item) {
    if (gameState.player.inventory.length < 20) {
        gameState.player.inventory.push(item);
        console.log(`将${item.name}放入背包`);
        updateInventoryDisplay();
        showEquipmentNotification(item.name, '放入背包');
    } else {
        console.log('背包已满，无法放入物品');
        // Drop item on ground
        dropItemOnGround(item);
    }
}

// Drop item on ground
function dropItemOnGround(item) {
    const dropX = gameState.player.x + (Math.random() - 0.5) * TILE_SIZE * 3;
    const dropY = gameState.player.y + (Math.random() - 0.5) * TILE_SIZE * 3;
    
    const droppedItem = {
        ...item,
        x: dropX,
        y: dropY
    };
    
    gameState.items.push(droppedItem);
    console.log(`背包已满，${item.name}掉落在地面上`);
    showEquipmentNotification(item.name, '掉落地面');
}

// Show equipment notification
function showEquipmentNotification(itemName, action) {
    const notification = document.createElement('div');
    notification.className = 'equipment-notification';
    notification.textContent = `${action}: ${itemName}`;
    
    // Set different colors for different actions
    let bgColor, textColor;
    if (action === '装备') {
        bgColor = 'rgba(0, 255, 0, 0.8)';  // Green for equip
        textColor = 'white';
    } else if (action === '放入背包') {
        bgColor = 'rgba(255, 165, 0, 0.8)';  // Orange for inventory
        textColor = 'white';
    } else {
        bgColor = 'rgba(255, 0, 0, 0.8)';  // Red for drop
        textColor = 'white';
    }
    
    notification.style.cssText = `
        position: fixed;
        top: 40%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: ${bgColor};
        color: ${textColor};
        padding: 10px 20px;
        border-radius: 5px;
        font-size: 16px;
        font-weight: bold;
        z-index: 10000;
        animation: equipmentFadeInOut 2s ease-in-out;
    `;
    
    // Add animation style if not exists
    if (!document.getElementById('equipment-animation-style')) {
        const style = document.createElement('style');
        style.id = 'equipment-animation-style';
        style.textContent = `
            @keyframes equipmentFadeInOut {
                0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); }
                50% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }
                100% { opacity: 0; transform: translate(-50%, -50%) scale(1); }
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(notification);
    
    // Remove notification after 2 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 2000);
}

// Update UI function
function updateUI() {
    // Update health bar
    const healthBar = document.querySelector('#health-bar');
    const healthText = document.getElementById('health-text');
    if (healthBar && healthText) {
        const healthPercent = gameState.player.health / gameState.player.maxHealth;
        healthBar.style.width = `${healthPercent * 100}%`;
        healthText.textContent = `${gameState.player.health}/${gameState.player.maxHealth}`;
        
        // Change color based on health percentage
        if (healthPercent > 0.6) {
            healthBar.style.background = 'linear-gradient(90deg, #ff4d4d, #ff6b6b)';
        } else if (healthPercent > 0.3) {
            healthBar.style.background = 'linear-gradient(90deg, #ffa500, #ffb347)';
        } else {
            healthBar.style.background = 'linear-gradient(90deg, #ff0000, #ff3333)';
        }
    }
    
    // Update experience bar
    const expBar = document.querySelector('#exp-bar');
    const expText = document.getElementById('exp-text');
    if (expBar && expText) {
        const expPercent = gameState.player.exp / gameState.player.maxExp;
        expBar.style.width = `${expPercent * 100}%`;
        expText.textContent = `${gameState.player.exp}/${gameState.player.maxExp}`;
    }
    
    // Update mana bar
    const manaBar = document.querySelector('#mana-bar');
    const manaText = document.getElementById('mana-text');
    if (manaBar && manaText) {
        const manaPercent = gameState.player.mana / gameState.player.maxMana;
        manaBar.style.width = `${manaPercent * 100}%`;
        manaText.textContent = `${gameState.player.mana}/${gameState.player.maxMana}`;
    }
    
    // Update player level
    const playerLevel = document.querySelector('.player-level');
    if (playerLevel) {
        playerLevel.textContent = `Lv.${gameState.player.level}`;
    }
    
    // Update attribute values
    const damageValue = document.getElementById('damage-value');
    const defenseValue = document.getElementById('defense-value');
    const speedValue = document.getElementById('speed-value');
    
    if (damageValue) damageValue.textContent = gameState.player.damage;
    if (defenseValue) defenseValue.textContent = gameState.player.defense;
    if (speedValue) speedValue.textContent = gameState.player.speed;
    
    // Update game stats
    const monsterCount = document.getElementById('monster-count');
    const itemCount = document.getElementById('item-count');
    
    if (monsterCount) monsterCount.textContent = gameState.monsters.length;
    if (itemCount) itemCount.textContent = gameState.items.length;
    
    // Update character panel if open
    updateCharacterPanel();
    
    // Update skills UI
    updateSkillsUI();
}

// Update character panel
function updateCharacterPanel() {
    // Update character basic info
    const charLevel = document.getElementById('char-level');
    const charName = document.getElementById('char-name');
    const charHealth = document.getElementById('char-health');
    const charExp = document.getElementById('char-exp');
    const charMana = document.getElementById('char-mana');
    
    if (charLevel) charLevel.textContent = gameState.player.level;
    if (charName) charName.textContent = '勇者';
    if (charHealth) charHealth.textContent = `${gameState.player.health}/${gameState.player.maxHealth}`;
    if (charExp) charExp.textContent = `${gameState.player.exp}/${gameState.player.maxExp}`;
    if (charMana) charMana.textContent = `${gameState.player.mana}/${gameState.player.maxMana}`;
    
    // Update character attributes
    const charDamage = document.getElementById('char-damage');
    const charDefense = document.getElementById('char-defense');
    const charMaxHealth = document.getElementById('char-max-health');
    const charSpeed = document.getElementById('char-speed');
    const charMaxMana = document.getElementById('char-max-mana');
    
    if (charDamage) charDamage.textContent = gameState.player.damage;
    if (charDefense) charDefense.textContent = gameState.player.defense;
    if (charMaxHealth) charMaxHealth.textContent = gameState.player.maxHealth;
    if (charSpeed) charSpeed.textContent = gameState.player.speed;
    if (charMaxMana) charMaxMana.textContent = gameState.player.maxMana;
    
    // Update equipment slots
    updateEquipmentSlots();
}

// Update equipment slots
function updateEquipmentSlots() {
    const weaponSlot = document.getElementById('weapon-slot');
    const chestSlot = document.getElementById('chest-slot');
    const ring1Slot = document.getElementById('ring1-slot');
    const ring2Slot = document.getElementById('ring2-slot');
    
    // Find equipped items
    const equippedWeapon = gameState.player.equipment?.weapon;
    const equippedChest = gameState.player.equipment?.chest;
    const equippedRings = gameState.player.equipment?.rings || [];
    
    if (weaponSlot) {
        if (equippedWeapon) {
            weaponSlot.innerHTML = `
                <div class="equipped-item">
                    <div class="item-name">${equippedWeapon.name}</div>
                    <div class="item-stats">
                        <span class="stat">攻击力: +${equippedWeapon.damage}</span>
                    </div>
                </div>
            `;
            weaponSlot.style.color = '#4a90e2';
            weaponSlot.style.background = 'rgba(74, 144, 226, 0.1)';
            weaponSlot.style.border = '2px solid #4a90e2';
        } else {
            weaponSlot.innerHTML = '<div class="empty-slot">未装备武器</div>';
            weaponSlot.style.color = '#666';
            weaponSlot.style.background = 'rgba(102, 102, 102, 0.1)';
            weaponSlot.style.border = '2px dashed #666';
        }
    }
    
    if (chestSlot) {
        if (equippedChest) {
            let statsHtml = `<span class="stat">防御力: +${equippedChest.defense}</span>`;
            if (equippedChest.health) {
                statsHtml += `<span class="stat">生命值: +${equippedChest.health}</span>`;
            }
            
            chestSlot.innerHTML = `
                <div class="equipped-item">
                    <div class="item-name">${equippedChest.name}</div>
                    <div class="item-stats">
                        ${statsHtml}
                    </div>
                </div>
            `;
            chestSlot.style.color = '#4a90e2';
            chestSlot.style.background = 'rgba(74, 144, 226, 0.1)';
            chestSlot.style.border = '2px solid #4a90e2';
        } else {
            chestSlot.innerHTML = '<div class="empty-slot">未装备护甲</div>';
            chestSlot.style.color = '#666';
            chestSlot.style.background = 'rgba(102, 102, 102, 0.1)';
            chestSlot.style.border = '2px dashed #666';
        }
    }
    
    if (ring1Slot) {
        if (equippedRings[0]) {
            let statsHtml = '';
            if (equippedRings[0].damage) statsHtml += `<span class="stat">攻击力: +${equippedRings[0].damage}</span>`;
            if (equippedRings[0].defense) statsHtml += `<span class="stat">防御力: +${equippedRings[0].defense}</span>`;
            if (equippedRings[0].health) statsHtml += `<span class="stat">生命值: +${equippedRings[0].health}</span>`;
            if (equippedRings[0].speed) statsHtml += `<span class="stat">速度: +${equippedRings[0].speed}</span>`;
            
            ring1Slot.innerHTML = `
                <div class="equipped-item">
                    <div class="item-name">${equippedRings[0].name}</div>
                    <div class="item-stats">
                        ${statsHtml}
                    </div>
                </div>
            `;
            ring1Slot.style.color = '#4a90e2';
            ring1Slot.style.background = 'rgba(74, 144, 226, 0.1)';
            ring1Slot.style.border = '2px solid #4a90e2';
        } else {
            ring1Slot.innerHTML = '<div class="empty-slot">未装备饰品</div>';
            ring1Slot.style.color = '#666';
            ring1Slot.style.background = 'rgba(102, 102, 102, 0.1)';
            ring1Slot.style.border = '2px dashed #666';
        }
    }
    
    if (ring2Slot) {
        if (equippedRings[1]) {
            let statsHtml = '';
            if (equippedRings[1].damage) statsHtml += `<span class="stat">攻击力: +${equippedRings[1].damage}</span>`;
            if (equippedRings[1].defense) statsHtml += `<span class="stat">防御力: +${equippedRings[1].defense}</span>`;
            if (equippedRings[1].health) statsHtml += `<span class="stat">生命值: +${equippedRings[1].health}</span>`;
            if (equippedRings[1].speed) statsHtml += `<span class="stat">速度: +${equippedRings[1].speed}</span>`;
            
            ring2Slot.innerHTML = `
                <div class="equipped-item">
                    <div class="stat">${equippedRings[1].name}</stat>
                    <div class="item-stats">
                        ${statsHtml}
                    </div>
                </div>
            `;
            ring2Slot.style.color = '#4a90e2';
            ring2Slot.style.background = 'rgba(74, 144, 226, 0.1)';
            ring2Slot.style.border = '2px solid #4a90e2';
        } else {
            ring2Slot.innerHTML = '<div class="empty-slot">未装备饰品</div>';
            ring2Slot.style.color = '#666';
            ring2Slot.style.background = 'rgba(102, 102, 102, 0.1)';
            ring2Slot.style.border = '2px dashed #666';
        }
    }
}

// Update skills UI
function updateSkillsUI() {
    const skillsButton = document.getElementById('skills-button');
    if (skillsButton) {
        const skillCount = Object.keys(gameState.player.skills).length;
        skillsButton.innerHTML = `
            <span class="btn-icon">🔮</span>
            <span class="btn-text">技能 (${skillCount})</span>
        `;
    }
}

// Setup UI handlers
function setupUIHandlers() {
    console.log('开始设置UI事件处理器...');
    
    // Setup inventory button
    const inventoryButton = document.getElementById('inventory-button');
    if (inventoryButton) {
        console.log('找到背包按钮，设置点击事件');
        inventoryButton.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            const inventoryPanel = document.getElementById('inventory-panel');
            if (inventoryPanel) {
                inventoryPanel.classList.toggle('hidden');
                updateInventoryDisplay();
                console.log('背包状态切换:', inventoryPanel.classList.contains('hidden') ? '关闭' : '打开');
            } else {
                console.error('找不到背包面板元素');
            }
        });
    } else {
        console.error('找不到背包按钮元素');
    }
    
    // Setup character button
    const characterButton = document.getElementById('character-button');
    if (characterButton) {
        console.log('找到角色按钮，设置点击事件');
        characterButton.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            const characterPanel = document.getElementById('character-panel');
            if (characterPanel) {
                characterPanel.classList.toggle('hidden');
                updateCharacterPanel();
                console.log('角色界面状态切换:', characterPanel.classList.contains('hidden') ? '关闭' : '打开');
            } else {
                console.error('找不到角色面板元素');
            }
        });
    } else {
        console.error('找不到角色按钮元素');
    }
    
    // Setup skills button
    const skillsButton = document.getElementById('skills-button');
    if (skillsButton) {
        console.log('找到技能按钮，设置点击事件');
        skillsButton.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            console.log('技能按钮被点击');
            
            const skillsPanel = document.getElementById('skills-panel');
            if (skillsPanel) {
                const isHidden = skillsPanel.classList.contains('hidden');
                if (isHidden) {
                    skillsPanel.classList.remove('hidden');
                    console.log('技能面板已打开');
                } else {
                    skillsPanel.classList.add('hidden');
                    console.log('技能面板已关闭');
                }
            } else {
                console.error('找不到技能面板元素');
            }
        });
    } else {
        console.error('找不到技能按钮元素');
    }
    
    // Setup map button
    const mapButton = document.getElementById('map-button');
    if (mapButton) {
        console.log('找到地图按钮，设置点击事件');
        mapButton.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            console.log('地图按钮被点击');
            
            const mapPanel = document.getElementById('map-panel');
            if (mapPanel) {
                const isHidden = mapPanel.classList.contains('hidden');
                if (isHidden) {
                    mapPanel.classList.remove('hidden');
                    updateMapPanel();
                    console.log('地图面板已打开');
                } else {
                    mapPanel.classList.add('hidden');
                    console.log('地图面板已关闭');
                }
            } else {
                console.error('找不到地图面板元素');
            }
        });
    } else {
        console.error('找不到地图按钮元素');
    }
    
    // Setup keyboard shortcuts
    document.addEventListener('keydown', (e) => {
        if (e.key === 'i' || e.key === 'I') {
            const inventoryPanel = document.getElementById('inventory-panel');
            if (inventoryPanel) {
                inventoryPanel.classList.toggle('hidden');
                updateInventoryDisplay();
                console.log('按I键切换背包面板');
            }
        } else if (e.key === 'c' || e.key === 'C') {
            const characterPanel = document.getElementById('character-panel');
            if (characterPanel) {
                characterPanel.classList.toggle('hidden');
                updateCharacterPanel();
                console.log('按C键切换角色面板');
            }
        } else if (e.key === 's' || e.key === 'S') {
            const skillsPanel = document.getElementById('skills-panel');
            if (skillsPanel) {
                const isHidden = skillsPanel.classList.contains('hidden');
                if (isHidden) {
                    skillsPanel.classList.remove('hidden');
                    console.log('按S键打开技能面板');
                } else {
                    skillsPanel.classList.add('hidden');
                    console.log('按S键关闭技能面板');
                }
            }
        } else if (e.key === 'm' || e.key === 'M') {
            const mapPanel = document.getElementById('map-panel');
            if (mapPanel) {
                const isHidden = mapPanel.classList.contains('hidden');
                if (isHidden) {
                    mapPanel.classList.remove('hidden');
                    updateMapPanel();
                    console.log('按M键打开地图面板');
                } else {
                    mapPanel.classList.add('hidden');
                    console.log('按M键关闭地图面板');
                }
            }
        } else if (e.key === 'Escape') {
            // Close all panels
            const panels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
            panels.forEach(panelId => {
                const panel = document.getElementById(panelId);
                if (panel && !panel.classList.contains('hidden')) {
                    panel.classList.add('hidden');
                    console.log(`按ESC键关闭${panelId}`);
                }
            });
        }
        
        // Skill shortcuts
        if (e.key === '1') {
            castSkill('fireball');
        } else if (e.key === '2') {
            castSkill('heal');
        } else if (e.key === '3') {
            castSkill('lightning');
        }
    });
    
    // Setup click outside to close panels
    document.addEventListener('click', (e) => {
        const inventoryPanel = document.getElementById('inventory-panel');
        const characterPanel = document.getElementById('character-panel');
        const skillsPanel = document.getElementById('skills-panel');
        const mapPanel = document.getElementById('map-panel');
        const inventoryButton = document.getElementById('inventory-button');
        const characterButton = document.getElementById('character-button');
        const skillsButton = document.getElementById('skills-button');
        const mapButton = document.getElementById('map-button');
        
        // Close inventory panel if clicking outside
        if (inventoryPanel && !inventoryPanel.classList.contains('hidden') && 
            !inventoryPanel.contains(e.target) && 
            !inventoryButton.contains(e.target)) {
            inventoryPanel.classList.add('hidden');
            console.log('点击外部区域，关闭背包');
        }
        
        // Close character panel if clicking outside
        if (characterPanel && !characterPanel.classList.contains('hidden') && 
            !characterPanel.contains(e.target) && 
            !characterButton.contains(e.target)) {
            characterPanel.classList.add('hidden');
            console.log('点击外部区域，关闭角色界面');
        }
        
        // Close skills panel if clicking outside
        if (skillsPanel && !skillsPanel.classList.contains('hidden') && 
            !skillsPanel.contains(e.target) && 
            !skillsButton.contains(e.target)) {
            skillsPanel.classList.add('hidden');
            console.log('点击外部区域，关闭技能面板');
        }
        
        // Close map panel if clicking outside
        if (mapPanel && !mapPanel.classList.contains('hidden') && 
            !mapPanel.contains(e.target) && 
            !mapButton.contains(e.target)) {
            mapPanel.classList.add('hidden');
            console.log('点击外部区域，关闭地图面板');
        }
    });
    
    // Prevent panels from closing when clicking inside them
    const inventoryPanel = document.getElementById('inventory-panel');
    const characterPanel = document.getElementById('character-panel');
    const skillsPanel = document.getElementById('skills-panel');
    const mapPanel = document.getElementById('map-panel');
    
    if (inventoryPanel) {
        inventoryPanel.addEventListener('click', (e) => {
            e.stopPropagation();
        });
    }
    
    if (characterPanel) {
        characterPanel.addEventListener('click', (e) => {
            e.stopPropagation();
        });
    }
    
    if (skillsPanel) {
        skillsPanel.addEventListener('click', (e) => {
            e.stopPropagation();
        });
    }
    
    if (mapPanel) {
        mapPanel.addEventListener('click', (e) => {
            e.stopPropagation();
        });
    }
    
    // Setup close button events
    const inventoryCloseBtn = document.getElementById('inventory-close-btn');
    const characterCloseBtn = document.getElementById('character-close-btn');
    const skillsCloseBtn = document.getElementById('skills-close-btn');
    const mapCloseBtn = document.getElementById('map-close-btn');
    
    if (inventoryCloseBtn) {
        inventoryCloseBtn.addEventListener('click', () => {
            if (inventoryPanel) {
                inventoryPanel.classList.add('hidden');
                console.log('点击关闭按钮，关闭背包');
            }
        });
    }
    
    if (characterCloseBtn) {
        characterCloseBtn.addEventListener('click', () => {
            if (characterPanel) {
                characterPanel.classList.add('hidden');
                console.log('点击关闭按钮，关闭角色界面');
            }
        });
    }
    
    if (skillsCloseBtn) {
        skillsCloseBtn.addEventListener('click', () => {
            if (skillsPanel) {
                skillsPanel.classList.add('hidden');
                console.log('点击关闭按钮，关闭技能面板');
            }
        });
    }
    
    if (mapCloseBtn) {
        mapCloseBtn.addEventListener('click', () => {
            const mapPanel = document.getElementById('map-panel');
            if (mapPanel) {
                mapPanel.classList.add('hidden');
                console.log('点击关闭按钮，关闭地图面板');
            }
        });
    }
    
    console.log('UI事件处理器设置完成');
}

// Update map panel
function updateMapPanel() {
    if (!mapManager) return;
    
    const currentMapData = mapManager.getCurrentMap();
    const currentMapCard = document.getElementById('current-map-card');
    const mapsList = document.getElementById('maps-list');
    
    // Update current map info
    if (currentMapCard) {
        currentMapCard.innerHTML = `
            <div class="map-name">${currentMapData.name}</div>
            <div class="map-level">推荐等级: ${currentMapData.level}</div>
            <div class="map-description">${currentMapData.description}</div>
        `;
    }
    
    // Update available maps list
    if (mapsList) {
        mapsList.innerHTML = '';
        const allMaps = mapManager.getAllMaps();
        
        allMaps.forEach(map => {
            const mapItem = document.createElement('div');
            mapItem.className = 'map-item';
            
            // Check if map is accessible
            const isAccessible = gameState.player.level >= map.level - 1;
            const isCurrentMap = map.id === mapManager.currentMapId;
            
            if (!isAccessible) {
                mapItem.classList.add('locked');
            }
            
            if (isCurrentMap) {
                mapItem.style.borderColor = '#4a90e2';
                mapItem.style.background = 'rgba(74, 144, 226, 0.2)';
            }
            
            mapItem.innerHTML = `
                <div class="map-item-name">${map.name}</div>
                <div class="map-item-level">推荐等级: ${map.level}</div>
                <div class="map-item-description">${map.description}</div>
            `;
            
            // Add click event for map selection (if accessible and not current)
            if (isAccessible && !isCurrentMap) {
                mapItem.addEventListener('click', () => {
                    // Switch to selected map
                    const newPosition = mapManager.switchMap(map.id);
                    if (newPosition) {
                        // Clear current monsters and items
                        gameState.monsters = [];
                        gameState.items = [];
                        
                        // Create new map
                        const newMapData = mapManager.getCurrentMap();
                        gameState.currentMap = new GameMap(newMapData);
                        gameState.currentMap.generate();
                        
                        // Set player position
                        gameState.player.x = newPosition.x;
                        gameState.player.y = newPosition.y;
                        
                        // Update UI
                        updateMapInfo();
                        updateMapPanel();
                        
                        // Close map panel
                        const mapPanel = document.getElementById('map-panel');
                        if (mapPanel) {
                            mapPanel.classList.add('hidden');
                        }
                        
                        console.log(`传送到: ${newMapData.name}`);
                        showMapNotification(`传送到: ${newMapData.name}`);
                    }
                });
            }
            
            mapsList.appendChild(mapItem);
        });
    }
}

// Update function
function update() {
    // Handle player movement
    if (keys['w'] || keys['W'] || keys['ArrowUp']) {
        gameState.player.direction = DIRECTIONS.UP;
        gameState.player.moving = true;
        const newY = gameState.player.y - PLAYER_SPEED;
        if (gameState.currentMap && gameState.currentMap.isWalkable(gameState.player.x / TILE_SIZE, newY / TILE_SIZE)) {
            gameState.player.y = newY;
        }
    } else if (keys['s'] || keys['S'] || keys['ArrowDown']) {
        gameState.player.direction = DIRECTIONS.DOWN;
        gameState.player.moving = true;
        const newY = gameState.player.y + PLAYER_SPEED;
        if (gameState.currentMap && gameState.currentMap.isWalkable(gameState.player.x / TILE_SIZE, newY / TILE_SIZE)) {
            gameState.player.y = newY;
        }
    } else if (keys['a'] || keys['A'] || keys['ArrowLeft']) {
        gameState.player.direction = DIRECTIONS.LEFT;
        gameState.player.moving = true;
        const newX = gameState.player.x - PLAYER_SPEED;
        if (gameState.currentMap && gameState.currentMap.isWalkable(newX / TILE_SIZE, gameState.player.y / TILE_SIZE)) {
            gameState.player.x = newX;
        }
    } else if (keys['d'] || keys['D'] || keys['ArrowRight']) {
        gameState.player.direction = DIRECTIONS.RIGHT;
        gameState.player.moving = true;
        const newX = gameState.player.x + PLAYER_SPEED;
        if (gameState.currentMap && gameState.currentMap.isWalkable(newX / TILE_SIZE, gameState.player.y / TILE_SIZE)) {
            gameState.player.x = newX;
        }
    } else {
        gameState.player.moving = false;
    }
    
    // Update camera to follow player
    gameState.camera.x = gameState.player.x - canvas.width / 2;
    gameState.camera.y = gameState.player.y - canvas.height / 2;
    
    // Spawn monsters periodically
    const currentMapData = mapManager ? mapManager.getCurrentMap() : null;
    if (currentMapData && Math.random() < currentMapData.spawnRate) {
        spawnMonsters();
    }
    
    // Check for portal interactions
    checkPortalInteraction();
    
    // Update monster AI
    updateMonsters();
    
    // Check collisions
    checkCollisions();
    
    // Update skill cooldowns
    updateSkillCooldowns();
    
    // Update UI
    updateUI();
}

// Update monsters AI
function updateMonsters() {
    gameState.monsters.forEach(monster => {
        // Simple AI: move towards player
        const dx = gameState.player.x - monster.x;
        const dy = gameState.player.y - monster.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < 150 && distance > 20) {
            // Move towards player
            const speed = 1;
            monster.x += (dx / distance) * speed;
            monster.y += (dy / distance) * speed;
        }
    });
}

// Check collisions
function checkCollisions() {
    // Check monster collisions
    gameState.monsters.forEach((monster, index) => {
        const dx = gameState.player.x - monster.x;
        const dy = gameState.player.y - monster.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < TILE_SIZE) {
            // Combat
            if (!gameState.player.inCombat) {
                gameState.player.inCombat = true;
                
                // Player attacks monster
                monster.health -= gameState.player.damage;
                console.log(`攻击${monster.name}，造成${gameState.player.damage}点伤害`);
                
                // Monster attacks player
                gameState.player.health -= monster.damage;
                console.log(`${monster.name}攻击，造成${monster.damage}点伤害`);
                
                // Check if monster is defeated
                if (monster.health <= 0) {
                    handleMonsterDefeat(monster);
                    gameState.monsters.splice(index, 1);
                }
                
                // Check if player is defeated
                if (gameState.player.health <= 0) {
                    gameState.player.health = 1;
                    console.log('玩家生命值过低，自动恢复');
                }
                
                // Reset combat flag after a delay
                setTimeout(() => {
                    gameState.player.inCombat = false;
                }, 1000);
            }
        }
    });
    
    // Check item collisions
    gameState.items.forEach((item, index) => {
        const dx = gameState.player.x - item.x;
        const dy = gameState.player.y - item.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < TILE_SIZE) {
            // Pick up item
            console.log(`拾取物品: ${item.name}，类型: ${item.type}`);
            
            // Try to auto-equip equipment items
            if (item.type === 'weapon' || item.type === 'armor' || item.type === 'accessory') {
                if (autoEquipItem(item)) {
                    // Item was equipped, remove from ground
                    gameState.items.splice(index, 1);
                    console.log(`${item.name}已自动装备`);
                } else {
                    // Item couldn't be equipped, add to inventory
                    if (gameState.player.inventory.length < 20) {
                        gameState.player.inventory.push(item);
                        gameState.items.splice(index, 1);
                        updateInventoryDisplay();
                        console.log(`${item.name}无法装备，已放入背包`);
                        showEquipmentNotification(item.name, '放入背包');
                    } else {
                        console.log('背包已满，无法拾取物品');
                    }
                }
            } else {
                // Non-equipment items go directly to inventory
                if (gameState.player.inventory.length < 20) {
                    gameState.player.inventory.push(item);
                    gameState.items.splice(index, 1);
                    updateInventoryDisplay();
                    console.log(`${item.name}已放入背包`);
                    showEquipmentNotification(item.name, '放入背包');
                } else {
                    console.log('背包已满，无法拾取物品');
                }
            }
        }
    });
}

// Handle monster defeat
function handleMonsterDefeat(monster) {
    // Give experience
    gameState.player.exp += monster.exp;
    
    // Check level up
    if (gameState.player.exp >= gameState.player.maxExp) {
        gameState.player.level++;
        gameState.player.exp -= gameState.player.maxExp;
        gameState.player.maxExp = Math.floor(gameState.player.maxExp * 1.5);
        gameState.player.maxHealth += 20;
        gameState.player.health = gameState.player.maxHealth;
        gameState.player.maxMana += 10;
        gameState.player.mana = gameState.player.maxMana;
        gameState.player.damage += 5;
        gameState.player.defense += 2;
        console.log(`升级！当前等级: ${gameState.player.level}`);
    }
    
    // Drop items
    if (Math.random() < monster.dropRate) {
        dropItem(monster.x, monster.y);
    }
}

// Drop item function
function dropItem(x, y) {
    console.log('尝试掉落物品，位置:', x, y);
    
    // 提高掉落率到80%
    if (Math.random() < 0.8) {
        const item = ITEM_TYPES[Math.floor(Math.random() * ITEM_TYPES.length)];
        const droppedItem = {
            ...item,
            x: x + (Math.random() - 0.5) * TILE_SIZE * 2,
            y: y + (Math.random() - 0.5) * TILE_SIZE * 2
        };
        
        gameState.items.push(droppedItem);
        console.log(`怪物掉落物品: ${item.name}，类型: ${item.type}`);
        
        // 显示掉落提示
        showDropNotification(item.name);
    } else {
        console.log('怪物没有掉落物品');
    }
}

// Show drop notification
function showDropNotification(itemName) {
    // 创建掉落提示元素
    const notification = document.createElement('div');
    notification.className = 'drop-notification';
    notification.textContent = `获得: ${itemName}`;
    notification.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 255, 0, 0.8);
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        font-size: 18px;
        font-weight: bold;
        z-index: 10000;
        animation: fadeInOut 2s ease-in-out;
    `;
    
    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes fadeInOut {
            0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); }
            50% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }
            100% { opacity: 0; transform: translate(-50%, -50%) scale(1); }
        }
    `;
    document.head.appendChild(style);
    
    document.body.appendChild(notification);
    
    // 2秒后移除提示
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 2000);
}

// Update skill cooldowns
function updateSkillCooldowns() {
    Object.values(gameState.player.skills).forEach(skill => {
        if (skill.cooldown > 0) {
            skill.cooldown--;
        }
    });
}

// Cast skill function
function castSkill(skillName) {
    const skill = gameState.player.skills[skillName];
    if (!skill || skill.cooldown > 0 || gameState.player.mana < skill.mana) {
        console.log(`技能${skill.name}冷却中、不存在或魔法值不足`);
        return false;
    }
    
    // Use mana
    gameState.player.mana -= skill.mana;
    
    // Set cooldown
    skill.cooldown = skill.maxCooldown;
    
    // Apply skill effects
    if (skillName === 'heal') {
        gameState.player.health = Math.min(gameState.player.maxHealth, gameState.player.health + skill.healing);
        console.log(`使用${skill.name}，恢复${skill.healing}点生命值`);
    } else if (skillName === 'fireball' || skillName === 'lightning') {
        // Find nearest monster and damage it
        let nearestMonster = null;
        let nearestDistance = Infinity;
        
        gameState.monsters.forEach(monster => {
            const distance = Math.sqrt(
                Math.pow(monster.x - gameState.player.x, 2) + 
                Math.pow(monster.y - gameState.player.y, 2)
            );
            if (distance < nearestDistance && distance < 200) {
                nearestDistance = distance;
                nearestMonster = monster;
            }
        });
        
        if (nearestMonster) {
            nearestMonster.health -= skill.damage;
            console.log(`使用${skill.name}，对${nearestMonster.name}造成${skill.damage}点伤害`);
            
            if (nearestMonster.health <= 0) {
                handleMonsterDefeat(nearestMonster);
                const index = gameState.monsters.indexOf(nearestMonster);
                if (index > -1) {
                    gameState.monsters.splice(index, 1);
                }
            }
        } else {
            console.log('没有找到目标');
        }
    }
    
    updateUI();
    return true;
}

// Check portal interaction
function checkPortalInteraction() {
    if (!mapManager || !gameState.currentMap) return;
    
    const portal = gameState.currentMap.checkPortal(gameState.player.x, gameState.player.y);
    if (portal) {
        // Check if player is high enough level for the target map
        const targetMapData = mapManager.maps.get(portal.targetMap);
        if (targetMapData && gameState.player.level >= targetMapData.level - 1) {
            // Switch to target map
            const newPosition = mapManager.switchMap(portal.targetMap);
            if (newPosition) {
                // Clear current monsters and items
                gameState.monsters = [];
                gameState.items = [];
                
                // Create new map
                const newMapData = mapManager.getCurrentMap();
                gameState.currentMap = new GameMap(newMapData);
                gameState.currentMap.generate();
                
                // Set player position
                gameState.player.x = newPosition.x;
                gameState.player.y = newPosition.y;
                
                // Update UI
                updateMapInfo();
                
                console.log(`传送到: ${newMapData.name}`);
                showMapNotification(`传送到: ${newMapData.name}`);
            }
        } else {
            console.log(`等级不足，无法进入 ${targetMapData.name} (需要等级 ${targetMapData.level})`);
            showMapNotification(`等级不足，无法进入 ${targetMapData.name}`);
        }
    }
}

// Update map info in UI
function updateMapInfo() {
    if (!mapManager) return;
    
    const currentMapData = mapManager.getCurrentMap();
    const mapInfoElement = document.getElementById('map-info');
    if (mapInfoElement) {
        mapInfoElement.innerHTML = `
            <div class="map-name">${currentMapData.name}</div>
            <div class="map-level">推荐等级: ${currentMapData.level}</div>
            <div class="map-description">${currentMapData.description}</div>
        `;
    }
    
    // Update monster count display
    const monsterCountElement = document.getElementById('monster-count');
    if (monsterCountElement) {
        monsterCountElement.textContent = `${gameState.monsters.length}/${currentMapData.monsterCount}`;
    }
}

// Show map notification
function showMapNotification(message) {
    const notification = document.createElement('div');
    notification.className = 'map-notification';
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(156, 39, 176, 0.9);
        color: white;
        padding: 15px 25px;
        border-radius: 8px;
        font-size: 18px;
        font-weight: bold;
        z-index: 10000;
        animation: mapNotificationFadeInOut 3s ease-in-out;
    `;
    
    // Add animation style if not exists
    if (!document.getElementById('map-notification-style')) {
        const style = document.createElement('style');
        style.id = 'map-notification-style';
        style.textContent = `
            @keyframes mapNotificationFadeInOut {
                0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); }
                20% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }
                80% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
                100% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(notification);
    
    // Remove notification after 3 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// Render function
function render() {
    // Clear canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // Save context for camera transformation
    ctx.save();
    ctx.translate(-gameState.camera.x, -gameState.camera.y);
    
    // Draw map
    if (gameState.currentMap) {
        gameState.currentMap.draw(ctx, gameState.camera);
    }
    
    // Draw items
    drawItems(ctx);
    
    // Draw monsters
    drawMonsters(ctx);
    
    // Draw player
    drawPlayer(ctx);
    
    // Restore context
    ctx.restore();
}

// Game loop
function gameLoop() {
    update();
    render();
    requestAnimationFrame(gameLoop);
}

// Initialize game
function initGame() {
    console.log('开始初始化游戏...');
    
    try {
        // Initialize map manager
        mapManager = new MapManager();
        
        // Initialize player equipment
        initPlayerEquipment();
        
        // Initialize current map
        const currentMapData = mapManager.getCurrentMap();
        gameState.currentMap = new GameMap(currentMapData);
        gameState.currentMap.generate();
        
        // Set player spawn position
        const spawnPoint = gameState.currentMap.getSpawnPoint();
        if (spawnPoint) {
            gameState.player.x = spawnPoint.x * TILE_SIZE;
            gameState.player.y = spawnPoint.y * TILE_SIZE;
        }
        
        // Spawn initial monsters
        spawnMonsters();
        
        // Setup UI
        createInventorySlots();
        setupUIHandlers();
        
        // Update UI with current map info
        updateMapInfo();
        
        console.log(`游戏初始化完成，当前地图: ${currentMapData.name}，开始游戏循环`);
        
        // Start game loop
        gameLoop();
        
    } catch (error) {
        console.error('游戏初始化失败:', error);
    }
}

// Key event listeners
document.addEventListener('keydown', (e) => {
    keys[e.key] = true;
});

document.addEventListener('keyup', (e) => {
    keys[e.key] = false;
});

// Start the game when page loads
window.addEventListener('load', () => {
    console.log('页面加载完成，开始初始化游戏...');
    setTimeout(() => {
    initGame();
    }, 100);
});

